package org.jwcloud.project.module.zx.upload.service;

import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;

import org.bson.types.ObjectId;
import org.jwcloud.project.module.zx.dao.RtaCMsgUploadFileDAO;
import org.jwcloud.project.module.zx.db.domain.RtaCMsgUploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.gridfs.GridFSDBFile;

@Service
public class FileUploadServiceImpl implements FileUploadService {

	@Autowired
	private RtaCMsgUploadFileDAO rtaCMsgUploadFileDAO;
	@Autowired
	private GridFsTemplate gridFsTemplate;

	@Override
	public RtaCMsgUploadFile saveFile(MultipartFile multipartFile) throws Exception {

		String fileName = multipartFile.getOriginalFilename();
		String contentType = multipartFile.getContentType();

		ObjectId objectId = gridFsTemplate.store(multipartFile.getInputStream(), fileName, contentType);
		String fileid = objectId.toString();

		RtaCMsgUploadFile rRtaCMsgUploadFile = new RtaCMsgUploadFile(); //

		rRtaCMsgUploadFile.setFileId(fileid);

		rRtaCMsgUploadFile.setFileName(fileName);
		String extName = new String();
		int dot = fileName.lastIndexOf('.');
		if ((dot > -1) && (dot < (fileName.length() - 1))) {
			extName = fileName.substring(dot + 1);
		}

		String filePath = fileid + "." + extName;
		rRtaCMsgUploadFile.setFilePath(filePath);
		rRtaCMsgUploadFile.setFileType(extName);
		rtaCMsgUploadFileDAO.create(rRtaCMsgUploadFile);
		return rRtaCMsgUploadFile;
	}

	@Override
	public InputStream getFile(String fileid) throws Exception {
		Query query = Query.query(Criteria.where("_id").is(fileid));
		InputStream inputStream = null;
		// 查询单个文件
		GridFSFile gridFsFile = gridFsTemplate.findOne(query);
		if (gridFsFile != null) {
			GridFsResource gridFsResource = gridFsTemplate.getResource(gridFsFile);
			inputStream = gridFsResource.getInputStream();
		}
		return inputStream;
	}

	@Override
	public RtaCMsgUploadFile searchFile(String fileid) throws IllegalStateException, IOException, Exception {
		// TODO Auto-generated method stub
		return (RtaCMsgUploadFile) rtaCMsgUploadFileDAO.findById(fileid);
	}

}
